﻿using Microsoft.EntityFrameworkCore;

namespace NET6.WebAPI.Extensions
{
    /// <summary>
    /// EF Core 扩展类
    /// </summary>
    public static class EfCoreExtension
    {
        /// <summary>
        /// 异步获取分页数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="queryable"></param>
        /// <param name="pages">第几页</param>
        /// <param name="pageRows">每页显示行数</param>
        /// <returns></returns>
        public static async Task<PageDto<T>> GetPageDataAsync<T>
            (this IQueryable<T> queryable, int pages, int pageRows) where T : class
        {
            int count = await queryable.CountAsync();
            var data = await queryable.Skip((pages - 1) * pageRows).Take(pageRows).ToListAsync();

            return new PageDto<T>(count, pageRows, data);
        }
    }

    /// <summary>
    /// 分页输出模型
    /// </summary>
    /// <typeparam name="T">使用泛型是方便对数据进行二次处理</typeparam>
    public class PageDto<T> where T : class
    {
        /// <summary>
        /// 总行数
        /// </summary>
        public int TotalRows { get; set; }

        /// <summary>
        /// 总页数
        /// </summary>
        public int TotalPages { get; set; }

        /// <summary>
        /// 当前页的数据
        /// </summary>
        public List<T> Data { get; set; }

        public PageDto(int totalRows, int pageRows, List<T> data)
        {
            TotalRows = totalRows;
            TotalPages = (int)Math.Ceiling((double)totalRows / pageRows);
            Data = data;
        }
    }
}
